package com.cloud.sso.oauth.handler;

import com.alibaba.fastjson.JSON;
import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.common.util.JsonContent;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

@Component
public class AppLoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        String result;
        if (e instanceof BadCredentialsException) {
            result = JSON.toJSONString(JsonContent.error(new AppException("密码错误")));
        } else if (e instanceof InternalAuthenticationServiceException) {
            result = JSON.toJSONString(JsonContent.error(new AppException(e.getMessage())));
        } else {
            result = JSON.toJSONString(JsonContent.error(new AppException(e.getMessage())));
        }

        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        Writer writer = httpServletResponse.getWriter();
        writer.write(result);
        writer.flush();
        writer.close();


    }
}
